package com.dylan.magic.guava.util;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;

import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author : ankang
 * @date : 2020/3/1 19:09
 * @Description :
 */
public class GuavaSyncCacheBuilder<K, V> {
    private CacheBuilder<K, V> cacheBuilder;

    public static GuavaSyncCacheBuilder<Object, Object> builder() {
        GuavaSyncCacheBuilder<Object, Object> builder = new GuavaSyncCacheBuilder<>();
        builder.cacheBuilder = CacheBuilder.newBuilder();
        return builder;
    }

    public GuavaSyncCacheBuilder<K, V> expireAfterWrite(Duration duration) {
        cacheBuilder.expireAfterWrite(duration);
        return this;
    }

    public GuavaSyncCacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
        cacheBuilder.expireAfterWrite(duration, unit);
        return this;
    }

    public GuavaSyncCacheBuilder<K, V> maximumSize(long maximumSize) {
        cacheBuilder.maximumSize(maximumSize);
        return this;
    }

    public GuavaSyncCacheBuilder<K, V> removalListener(RemovalListener<? super K, ? super V> listener) {
        cacheBuilder.removalListener(listener);
        return this;
    }

    public LoadingCache<K, V> build(Function<K, V> function) {
        return cacheBuilder.build(GuavaCacheUtil.buildSyncCacheLoader(function));
    }
}
